<?php

namespace Respect\Http\Module;

use Respect\Http\Bootstrappable;

abstract class NegotiationAbstract implements Bootstrappable
{

    protected $requested = array();
    protected $negotiated;

    protected function parseHeader($acceptHeader)
    {
        $accept = array();
        $acceptHeader = strtolower(str_replace(' ', '', $acceptHeader));
        $acceptList = explode(',', $acceptHeader);
        foreach ($acceptList as $acceptPart) {
            if (strpos($acceptPart, 'q=') === false) {
                $quality = 1;
            } else {
                list($acceptPart, $quality) = explode(';q=', $acceptPart);
            }
            $accept[$acceptPart] = (int) ($quality * 1000);
        }
        return $accept;
    }

    public function negotiate($availableMimetypes)
    {
        if (!is_null($this->negotiated)) {
            return $this->negotiated;
        }
        foreach ($this->requested as $requested => $rate) {
            foreach ($availableMimetypes as $available) {
                if ($requested === $available) {
                    return $this->negotiated = $available;
                }
            }
        }
    }

}